package org.jeecg.modules.iot.mqtt.server;/*
package org.jeecg.mqtt.server;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.equ.common.feign.IRentalCarAPI;
import org.equ.common.model.entity.EquTerminal;
import org.equ.common.model.entity.RentalCar;

import org.equ.common.model.vo.EquTerminalQueryVo;
import org.equ.common.model.vo.RentalCarQueryVo;
import org.jeecg.common.api.vo.Result;

import org.jeecg.mqtt.cache.EBikeCache;
import org.jeecg.mqtt.config.MqttProperties;
import org.jeecg.mqtt.entity.ClientConnectEvent;
import org.jeecg.mqtt.entity.MqttMessageJson;
import org.jeecg.mqtt.model.cabinet.CabinetHeartbeatData;
import org.jeecg.mqtt.model.cabinet.CabinetOpenDoorData;
import org.jeecg.mqtt.model.cabinet.CabinetRegisterData;
import org.jeecg.mqtt.model.cabinet.CabinetSwapData;
import org.jeecg.mqtt.model.socket.CloseAndOpenResponse;
import org.jeecg.mqtt.model.socket.DeviceHeartbeatData;
import org.jeecg.mqtt.model.socket.DeviceReportData;
import org.jeecg.mqtt.server.service.MessageHandlerService;
import org.jeecg.mqtt.server.service.RecvMessageHandlerService;

import org.jeecg.mqtt.server.service.processor.cabinet.CabinetProcessor;
import org.jeecg.mqtt.server.service.processor.socketOperate.ChargePileProcessor;
import org.jeecg.utils.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.yzh.protocol.codec.JTMessageAdapter;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantLock;
import java.util.regex.Pattern;

*/
/**
 * @Description : MQTT接受服务的回调类
 * @Author : Sherlock
 * @Date : 2023/8/1 16:29
 *//*

@Slf4j
@Component
public class MqttAcceptCallback implements MqttCallbackExtended {

    private static final Logger logger = LoggerFactory.getLogger(MqttAcceptCallback.class);
    public static final JTMessageAdapter coder = new JTMessageAdapter("org.yzh.protocol");
    private final Pattern serverCallDevicePattern = Pattern.compile("/([^/]+)/([^/]+)/user/get");
    private final Pattern deviceReportPattern = Pattern.compile("/([^/]+)/([^/]+)/user/update");

    @Autowired
    private MqttAcceptClient mqttAcceptClient;

    @Autowired
    private MqttSendClient mqttSendClient;

    @Autowired
    private EBikeCache vehicleCache;

    @Autowired
    private ChargePileProcessor chargePileProcessor;
    @Autowired
    private CabinetProcessor cabinetProcessor;

    @Autowired
    private MqttProperties mqttProperties;
   */
/* @Autowired
    private RentalCarMapper rentalCarMapper;

    @Autowired
    private EquTerminalMapper equTerminalMapper;*//*


    @Autowired
    private IRentalCarAPI iRentalCarAPI;

    @Autowired
    private MessageHandlerService messageHandlerService;
    @Autowired
    private RecvMessageHandlerService recvMessageHandlerService;

    */
/*多线程处理*//*

    private ExecutorService executorService = Executors.newCachedThreadPool() ; // 创建一个固定大小的线程池


    private final ReentrantLock lock = new ReentrantLock();
    */
/**
     * 客户端断开后触发
     *
     * @param throwable
     *//*

    @Override
    public void connectionLost(Throwable throwable) {

        executorService.execute(() -> {
        logger.info("连接断开，可以重连");
        try {
            lock.lock();
        if (MqttAcceptClient.client == null || !MqttAcceptClient.client.isConnected()) {
            while (!MqttAcceptClient.client.isConnected()) {
                logger.info("【emqx重新连接】....................................................");
                Thread.sleep(5000);
                mqttAcceptClient.reconnection();
            }

        }
        } catch (InterruptedException e) {
            // 处理异常
            Thread.currentThread().interrupt();
        e.printStackTrace();
        }catch (Exception e){
        e.printStackTrace();
        }finally {
            lock.unlock();
        }

        });
    }

    */
/**
     * 客户端收到消息触发
     *
     * @param topic       主题
     * @param mqttMessage 消息
     *//*

    @Override
    public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
        executorService.execute(() -> {
        try {
            logger.info("【接收消息主题】:" + topic);
            logger.info("【接收消息Qos】:" + mqttMessage.getQos());
            logger.info("【接收消息内容】:" + new String(mqttMessage.getPayload()));

            System.out.println("messageArrived executed in thread: " + Thread.currentThread().getName());
            //接收数据判断数据是否符合格式
            ObjectMapper objectMapper = new ObjectMapper();
            String payload = new String(mqttMessage.getPayload());
            */
/*test部分*//*

            payload=extractJsonData(payload);

            boolean isJson = JsonUtil.is808Json(payload);
            boolean isCabinetJson = JsonUtil.isCabinetJson(payload);
            boolean  isChargePileJson=JsonUtil.isChargePileJson(payload);
            boolean  isClientConnectJson=JsonUtil.isClientConnectJson(payload);
            if (isChargePileJson){
                if (isTopicMatchedWithWildcard(topic, mqttProperties.getZnczTopic())) {
                    // 解析 JSON 数据并返回相应的实体类
                    Object parsedData = JsonUtil.parseJsonData(payload);
                    if (parsedData instanceof DeviceHeartbeatData) {
                        chargePileProcessor.handleDeviceHeartbeat((DeviceHeartbeatData) parsedData);
                    }else if (parsedData instanceof DeviceReportData) {
                        chargePileProcessor. handleDeviceReport((DeviceReportData) parsedData);
                    }else if (parsedData instanceof CloseAndOpenResponse) {
                        chargePileProcessor. handleCloseAndOpen((CloseAndOpenResponse) parsedData);
                    }
                } else if (isDeviceReportTopic(topic)) {
                    //
                    System.out.println("device");
                }
            } else if (isJson) {
                //映射JSON 类
                MqttMessageJson mqttMessageJson = new MqttMessageJson();
                mqttMessageJson = objectMapper.readValue(payload, MqttMessageJson.class);
               */
/*  if (!"865376074560937".equals(mqttMessageJson.getId())){
                    return;
                }*//*

               */
/* if (!"0200".equals(mqttMessageJson.getCmd())){
                    return;
                }*//*

                System.out.println("【接收消息主题】:" + topic);
                System.out.println("【接收消息Qos】:" + mqttMessage.getQos());
                System.out.println("【接收消息内容】:" + new String(mqttMessage.getPayload()));

                MqttMessageJson mqttMessageJsonReturn = new MqttMessageJson();



                //判断主题是哪一个
                if (isTopicMatchedWithWildcard(topic, mqttProperties.getSendTopic())) {
                    messageHandlerService.handleDeviceSendMessage(mqttMessageJson, mqttMessageJsonReturn);

                } else if (mqttProperties.getRecvTopic().equals(topic)) {
                    recvMessageHandlerService.handleIotRecvMessage(mqttMessageJson);
                }
                //响应
                if (mqttMessageJsonReturn != null&&mqttMessageJsonReturn.getId()!=null) {
                    String returnJson = objectMapper.writeValueAsString(mqttMessageJsonReturn);
                    mqttSendClient.publish(true, mqttMessageJson.getId(), returnJson);
                }
            }else if (isCabinetJson){
                if (isTopicMatchedWithWildcardCabinet(topic, mqttProperties.getCabinetTopic())) {
                    // 解析 JSON 数据并返回相应的实体类
                    Object parsedData = JsonUtil.parseCabinetJsonData(payload);
                    if (parsedData instanceof CabinetRegisterData) {
                        cabinetProcessor.handleDeviceRegister((CabinetRegisterData) parsedData);
                    } else if (parsedData instanceof DeviceHeartbeatData) {
                        cabinetProcessor.handleDeviceHeartbeat((CabinetHeartbeatData) parsedData);
                    } else if (parsedData instanceof CabinetSwapData) {
                        cabinetProcessor.handleDeviceSwap((CabinetSwapData) parsedData);
                    } else if (parsedData instanceof CabinetOpenDoorData) {
                        cabinetProcessor.handleDeviceOpenDoor((CabinetOpenDoorData) parsedData);
                    }
                } else if (isDeviceReportTopic(topic)) {
                    // 处理其他设备报告的主题
                    System.out.println("device");
                }
            }else if (isClientConnectJson){

                ClientConnectEvent clientConnectEvent = new ClientConnectEvent();
                clientConnectEvent = objectMapper.readValue(payload, ClientConnectEvent.class);
                String clientId = clientConnectEvent.getClientid();

                String status = "client.connected".equals(clientConnectEvent.getEvent()) ? "online" : "offline";
                vehicleCache.setVehicleOnlineStatus(clientId,status);
                createCarIfNotExists(clientId);

            }

        }  catch (Exception e) {
        logger.error("MqttAcceptCallback messageArrived error,message:{}", e.getMessage());
        e.printStackTrace();
    }
        });
    }

    */
/**
     * 发布消息成功
     *
     * @param token token
     *//*

    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {

        String[] topics = token.getTopics();
        for (String topic : topics) {
            logger.info("向主题【" + topic + "】发送消息成功！");
        }
        try {
            MqttMessage message = token.getMessage();
            byte[] payload = message.getPayload();
            String s = new String(payload, "UTF-8");
            logger.info("【消息内容】:" + s);
        } catch (Exception e) {
            logger.error("MqttAcceptCallback deliveryComplete error,message:{}", e.getMessage());
            e.printStackTrace();
        }


    }


    public void createCarIfNotExists(String carCode) {
        synchronized (this){
            // 去掉手机号前三位
            String formattedPhoneNumber = carCode.substring(3);

            //添加到 EquTerminal 中控表

            EquTerminalQueryVo equTerminalQueryVo = new EquTerminalQueryVo();
            equTerminalQueryVo.setTerminalCode(carCode); // Set the terminalId in the QueryVo

            Result<List<EquTerminal>> equTerminalsResult = iRentalCarAPI.listEquTerminals(equTerminalQueryVo);

            if (equTerminalsResult.isSuccess() && equTerminalsResult.getResult().isEmpty()) { // Check for success and empty list
                // 2. Use addTerminal to insert
                EquTerminal equTerminal = new EquTerminal();
                equTerminal.setTerminalId(carCode);
                equTerminal.setTerminalSn(formattedPhoneNumber);
                equTerminal.setTerminalImei(carCode);
                equTerminal.setBlueKey("138CA800BD567D52AE92FF63FB537E56");

                Result<String> addResult = iRentalCarAPI.addTerminal(equTerminal);

                if (!addResult.isSuccess()) {

                    log.error("Failed to add EquTerminal: {}", addResult.getMessage());

                }
            } else if (!equTerminalsResult.isSuccess()) {

                log.error("Failed to query EquTerminals: {}", equTerminalsResult.getMessage());

            }





            RentalCarQueryVo rentalCarQueryVo=new RentalCarQueryVo();
            rentalCarQueryVo.setCarCode(carCode);
            Result<List<RentalCar>> result = iRentalCarAPI.listByQuery(rentalCarQueryVo);




            if (result != null && result.isSuccess() && (result.getResult() == null || result.getResult().isEmpty())) { // 判断是否为空或空列表
                RentalCar newCar = new RentalCar();
                newCar.setCarCode(carCode);
                newCar.setPhone(formattedPhoneNumber);
                newCar.setMeshPointId(1817812669558865922L);
                newCar.setSysOrgCode("A03A01");
                newCar.setCarTypeId(1801890634773512194L);
                newCar.setBlueKey("138CA800BD567D52AE92FF63FB537E56");
                newCar.setTerminalType("G56");
                // 设置其他必要的属性

                //  调用 Feign 接口创建新车辆，而不是本地数据库
                Result<Boolean> createResult = iRentalCarAPI.createRentalCar(newCar); //  假设 iRentalCarAPI 提供了 createRentalCar 方法

                if (createResult == null || !createResult.isSuccess() || !createResult.getResult()) {
                    log.error("创建车辆失败，carCode: {}, error: {}", carCode, createResult);
                    //  根据实际情况进行错误处理
                }
            } else if (result == null || !result.isSuccess()) {
                log.error("查询车辆失败，carCode: {}, error: {}", carCode, result);
                //  根据实际情况进行错误处理
            }
        }

    }
    private void handleDeviceHeartbeat(DeviceHeartbeatData data) {
        // 处理设备心跳逻辑
        System.out.println("处理设备心跳逻辑: " + data.toString());
    }
    */
/**
     * 连接emq服务器后触发
     *
     * @param b
     * @param s
     *//*

    @Override
    public void connectComplete(boolean b, String s) {
        //logger.info("============================= 客户端【" + MqttAcceptClient.client.getClientId() + "】连接成功！=============================");
        // 以/#结尾表示订阅所有以test开头的主题
        // 订阅所有机构主题
        mqttAcceptClient.subscribe(mqttProperties.getDefaultTopic(), 0);
        mqttAcceptClient.subscribe(mqttProperties.getRecvTopic(), 1);
        mqttAcceptClient.subscribe(mqttProperties.getSendTopic(), 1);
        mqttAcceptClient.subscribe(mqttProperties.getZnczTopic(), 1);
        mqttAcceptClient.subscribe(mqttProperties.getCabinetTopic(), 1);
        mqttAcceptClient.subscribe(mqttProperties.getDeviceStatus(), 1);

    }

    private static String  getTopic(String deviceId){
        return "/device/" + deviceId + "/recv";
    }

    public static String extractJsonData(String input) {
        try {
            int startIndex = input.indexOf("{");
            int endIndex = input.lastIndexOf("}") + 1;
            return input.substring(startIndex, endIndex);
        } catch (Exception e) {
            // 处理异常情况
            System.out.println("Error extracting JSON data: " + e.getMessage());
            return null;
        }
    }
    private boolean isServerCallDeviceTopic(String topic) {
        return serverCallDevicePattern.matcher(topic).matches();
    }
    */
/*private boolean isServerCallDeviceTopic(String topic) {
        String productKeyPattern = "[^/]+";
        String imeiNamePattern = "[^/]+";
        String serverCallDevicePattern = String.format("/%s/%s/user/get", productKeyPattern, imeiNamePattern);
        return Pattern.matches(serverCallDevicePattern, topic);
    }*//*


    private boolean isDeviceReportTopic(String topic) {
        return deviceReportPattern.matcher(topic).matches();
    }

   */
/* private boolean isDeviceReportTopic(String topic) {
        String productKeyPattern = "[^/]+";
        String imeiNamePattern = "[^/]+";
        String deviceReportPattern = String.format("/%s/%s/user/update", productKeyPattern, imeiNamePattern);
        return Pattern.matches(deviceReportPattern, topic);
    }*//*

    public static boolean isTopicMatchedWithWildcard(String topic, String wildcardTopic) {
        String[] topicParts = topic.split("/");
        String[] wildcardParts = wildcardTopic.split("/");

        // 检查主题长度是否匹配
        if (topicParts.length != wildcardParts.length) {
            return false;
        }

        for (int i = 0; i < wildcardParts.length; i++) {
            String wildcardPart = wildcardParts[i];
            String topicPart = topicParts[i];

            // 如果通配符为 +,则匹配任何值
            if (wildcardPart.equals("+")) {
                continue;
            }
            // 如果通配符为 #,则必须在最后一个位置,且后面不能有其他字符
            else if (wildcardPart.equals("#")) {
                return i == wildcardParts.length - 1 && topicParts.length == wildcardParts.length;
            }
            // 如果不是通配符,则必须完全匹配
            else if (!wildcardPart.equals(topicPart)) {
                return false;
            }
        }

        return true;
    }


    private boolean isCabinetJson(String payload) {
        // 判断 payload 是否是换电柜相关的 JSON 数据
        // 实现具体的判断逻辑
        return true;
    }

    private boolean isTopicMatchedWithWildcardCabinet(String topic, String wildcardTopic) {
        // 判断 topic 是否与通配符主题匹配
        // 实现具体的匹配逻辑
        return true;
    }



}*/
